package com.wgh.demo.ai.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.wgh.demo.ai.config.AiModelConfig;
import com.wgh.demo.ai.enums.AiModelType;
import com.wgh.demo.ai.service.AiModelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Arrays;

@Service
public class AlibabaAiModelServiceImpl implements AiModelService {
    private static final Logger logger = LoggerFactory.getLogger(AlibabaAiModelServiceImpl.class);

    @Autowired
    private AiModelConfig aiModelConfig;

    @Override
    public Mono<String> generateText(String prompt) {
        return Mono.fromCallable(() -> {
            // 设置API密钥
            String apiKey = aiModelConfig.getAlibaba().getApiKey();
            Constants.apiKey = apiKey;
            logger.info("阿里AI大模型API密钥已设置，长度: {}", apiKey.length());

            // 初始化阿里AI大模型客户端
            Generation generation = new Generation();

            // 构建请求参数
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(prompt)
                    .build();

            GenerationParam param = GenerationParam.builder()
                    .model("qwen-plus") // 使用阿里通义千问模型
                    .messages(Arrays.asList(userMsg))
                    .maxTokens(1000)
                    .temperature(0.7f)
                    .build();

            logger.info("阿里AI大模型请求参数: {}", param);

            // 发送请求
            GenerationResult result = generation.call(param);

            logger.info("阿里AI大模型响应结果: {}", result);

            // 处理响应
            logger.info("阿里AI大模型响应输出: {}", result.getOutput());
            if (result.getOutput() != null) {
                logger.info("阿里AI大模型响应选项: {}", result.getOutput().getChoices());
                if (result.getOutput().getChoices() != null && !result.getOutput().getChoices().isEmpty()) {
                    logger.info("阿里AI大模型响应消息: {}", result.getOutput().getChoices().get(0).getMessage());
                    if (result.getOutput().getChoices().get(0).getMessage() != null) {
                        return result.getOutput().getChoices().get(0).getMessage().getContent();
                    } else {
                        logger.error("阿里AI大模型响应消息为空: {}", result);
                        return "阿里AI大模型响应消息为空，请稍后再试";                     
                    }
                } else {
                    // 尝试直接获取文本响应（可能SDK版本不同导致结构变化）
                    if (result.getOutput() != null && result.getOutput().getText() != null && !result.getOutput().getText().isEmpty()) {
                        logger.info("直接获取阿里AI大模型文本响应: {}", result.getOutput().getText());
                        return result.getOutput().getText();
                    } else {
                        logger.error("阿里AI大模型响应选项为空: {}", result);
                        throw new RuntimeException("阿里AI大模型响应选项为空，请稍后再试");                      
                    }
                }
            } else {
                logger.error("阿里AI大模型响应输出为空: {}", result);
                throw new RuntimeException("阿里AI大模型响应输出为空，请稍后再试");            
            }
        }).onErrorResume(e -> {
            if (e instanceof NoApiKeyException) {
                logger.error("API密钥未设置: {}", e.getMessage(), e);
                return Mono.just("API密钥未设置，请检查配置");
            } else if (e instanceof ApiException) {
                logger.error("调用阿里AI大模型失败: {}", e.getMessage(), e);
                return Mono.just("调用阿里AI大模型失败: " + e.getMessage());
            } else if (e instanceof RuntimeException) {
                return Mono.just(e.getMessage());
            } else {
                logger.error("调用阿里AI大模型发生未知错误: {}", e.getMessage(), e);
                return Mono.just("调用阿里AI大模型发生未知错误，请稍后再试");
            }
        });
    }

    @Override
    public String getModelName() {
        return AiModelType.ALIBABA.getCode();
    }
}